<script setup lang="ts">
import { ref, watch } from 'vue';
import type { QuestionItem } from '#/types/question';
import QuestionHeader from './question-header.vue';
import { debounceFn } from "#/utils/debounce";
import { QUESTION_STATUS } from '../../const';

interface Props {
  question: QuestionItem;
  questionIndex: number;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  updateStatus: [questionItem: QuestionItem, status: typeof QUESTION_STATUS.ANSWERED | typeof QUESTION_STATUS.UNANSWERED | typeof QUESTION_STATUS.MARKED, isMarked?: boolean];
  updateAnswer: [questionId: string | number | null, answer: any];
}>();

const selectedAnswers = ref<string[]>([]);
const isMarked = ref(false);

// 初始化答案和状态
watch(() => props.question, (newQuestion) => {
  if (newQuestion.answer) {
    // const answerList = JSON.parse(newQuestion.answer as string) || [];
    const answerList = newQuestion.answer || [] as any;
    selectedAnswers.value = answerList?.map((item: any) => item?.id || '') || [];
  }
  isMarked.value = newQuestion.markDoubtful || false;
}, { immediate: true });

// 处理选项变化
const handleAnswerChange = debounceFn((value: string[]) => {
  selectedAnswers.value = value;
  const answer = value.map(item => ({ id: item }));
  emit('updateAnswer', props.question.id, answer);
  emit('updateStatus',
    props.question,
    value.length > 0 ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED,
    isMarked.value);
}, 500);

// 处理存疑操作
const handleMark = () => {
  isMarked.value = !isMarked.value;
  const status = isMarked.value ? QUESTION_STATUS.MARKED : (selectedAnswers.value.length > 0 ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED);
  emit('updateStatus', props.question, status, isMarked.value);
};

// 获取选项列表
const options = props.question.originalData?.options || [];
</script>

<template>
  <div class="checkbox-question" :data-question-id="question.id">
    <QuestionHeader :question-index="questionIndex" :stem="question.originalData?.stem || ''"
      :score="question.originalData?.score || 0" :is-marked="isMarked" @mark="handleMark" />

    <!-- <div v-if="question.originalData?.stemImg" class="question-image mb-4">
      <img :src="question.originalData.stemImg" alt="题目图片" class="max-w-full h-auto" />
    </div> -->

    <el-checkbox-group v-model="selectedAnswers" @change="handleAnswerChange" class="ml-4">
      <el-checkbox :value="option.id" class="w-full" v-for="option in options" :key="option.id">
        <span class="option-label">{{ option.name }}. {{ option.content }}</span>
        <!-- <img v-if="option.path" :src="option.path" alt="选项图片" class="max-w-xs h-auto ml-2" /> -->
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<style scoped>
.option-label {
  font-weight: 400;
  font-size: 12px;
}
</style>
